<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<link rel="stylesheet" href="../css/mui.min.css">
	<script src="../js/app.js"></script>
	<script src="../js/mui.min.js"></script>
	<title>Document</title>
	<style type="text/css">  
select{
	padding: 3px;
	margin: 2px;
	font-size: 17px;
}
textarea{
	width:98%;margin-left:1%;margin-top: 1px;font-size: 17px;
}
</style> 
</head>
<body>
	<header class="mui-bar mui-bar-nav">
	    <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
	    <h1 class="mui-title">发布</h1>
	</header>
<div id="uploader" class="mui-content"style="font-size: 17px;">
   <div id="result" name="result" style="margin-left:1px;"></div> 
   <div onclick="addImage(9)" style="width:100px;margin:6px;float:left;height:100px;padding:10px;" ><img  style="float:initial;width:80px;" src="../images/iconfont-tianjia.png"/></div>
   <textarea maxlength="300" type="text" name="mess" id="mess" rows="3" cols="30" placeholder="请输入文字内容"></textarea>
       <!--<div style="margin-left: 0;margin-top: 20px;font-size: 17px;width:100%;float:left;"  class="select">-->
       <div id="guanlian" name="guanlian" style="width:100%;float:left;margin-top: -12px;">
    <div style="width:16%;float:left;margin-left:3px;padding: 5px;">关联:</div>
    <select id="opta"style="width:28%;" onchange="getsel()">
  <option value="0">请选择类别</option>
  <option value="xiangmu">项目</option>
  <option value="ziyuan">资源</option>
  <option value="jishu">技术</option>
  <option value="qita">其他</option>
 </select> 
 <select id="optb" style="width:50%;" >
  <option value="0">选择您发布的资源</option>
 </select>
   </div>
    <button type="button" data-loading-text="提交中" onclick="addup()"  style="float:right;margin-right: 1%;width: 98%;margin-top: 8px;" class="mui-btn mui-btn-primary">发送</button>
    <button type="button" data-loading-text="提交中" onclick="ceshi()"  style="float:right;margin-right: 1%;width: 98%;margin-top: 8px;" class="mui-btn mui-btn-primary">测试</button>
</div>
<script type="text/javascript" > 
//optData={"mtoken":home.mtoken,"usertoken":my.token,"mid":my.mid,"authdate":my.authdate};
mui.post(home.hos+'/user/item',apptoken,function(data){
		//服务器返回响应，根据响应结果，分析是否登录成功;
	},'json'
); 

var listJson={'0':'选择关联类','item':'项目','ziyuan':'资源','jishu':'技术','qita':'其他'};
var opta=document.getElementById("opta");
var i=0;
var lisk='';
for(var p in listJson){//遍历json对象的每个key/value对,p为key
	lisk+='<option value="'+p+'">'+listJson[p]+'</option>';
}
opta.innerHTML='<select id="opta"style="width:28%;" onchange="getsel()">'+lisk+' </select> ';


function getsel(){
	//去本地数据库读取个人发布的信息，字段key=opta.value;
var optb=document.getElementById("optb");
if(opta.value=='0'){
		optb.innerHTML='<option value="0">请选择您的资源</option>';
		return false;}
result=injsonstr('',opta.value)||[];//自定义函数从本地数据库取出并且转换成数组
if(result.length===0){alert('对不起不存在'+listJson[opta.value]+'信息,请您发布该类信息后，再添加关联！');return false;};
//key是本地数据库的键值，
var vals='';
for(var i=0;i<result.length;i++){
	vals += '"'+result[i].id+'":"'+result[i].title+'",';
		}
	vals=vals.substring(0, vals.lastIndexOf(',')); //去尾字符]
var listval=JSON.parse('{'+vals+'}');
var val='';
	for(var pb in listval){
		val +='<option value="'+pb+'">'+listval[pb]+'</option>';
	}
	optb.innerHTML='<select id="optb"style="width:28%;" onchange="">'+val+' </select> ';
}

//压缩图片，这个比较变态的方法，无法return  
function compressImage(src,dstname) {  
    //var dstname="_downloads/"+getUid()+".jpg";  
    plus.zip.compressImage({  
            src: src,  
            dst: dstname,  
            overwrite:true,  
            quality: 20  
        },  
        function(event) {  
            return event.target;  
        },  
        function(error) {  
            console.log(error);  
            return src;  
        });  
}  

function addImage(maxnum){
	maxnum=maxnum || 9;
	var num=0;//最多允许上传文件个数
	var imgs=localStorage.getItem('img')||"";
	if(imgs!=''){
		imgstr =imgs.substring(0, imgs.lastIndexOf(','));//去掉末尾逗号
	imgarr = eval('(['+imgs+'])');//字符串转成json对象
	num=imgarr.length||0;
	if(imgarr.length>maxnum){
		alert("对不起最多只能选择9张图片");
		return false;
	};
	}
	var lasnum=maxnum-num;//最多还允许上传文件个数
            if (mui.os.plus) {  
                var a = [{  
                    title: "拍照"  
                }, {  
                    title: "从手机相册选择"  
                }];  
                plus.nativeUI.actionSheet({  
                    title: "修改用户头像",  
                    cancel: "取消",  
                    buttons: a  
                }, function(a) { /*actionSheet 按钮点击事件*/  
                    switch (a.index) {  
                        case 0:break;
                        case 1:getImage();break; /*拍照*/  
//                      case 2:appendByGallery();/*打开相册*/  
                       case 2: gallery(maxnum,lasnum);//打开相册
                    }  
                })  
            }} 

//var thisid="";
function deleteimg(thisid){//删除图片
if(!window.confirm('你确定要删除吗？')){
                 //alert("确定");
                 return false;
             }
	var tid=document.getElementById(thisid);
	var result=document.getElementById("result");  
imgs=localStorage.getItem('img');//读取本地数据库
imgs =imgs.substring(0, imgs.lastIndexOf(','));//去掉末尾逗号
imgs = eval('(['+imgs+'])');//字符串转成json对象
var imgss="";
for(var i=0;i<imgs.length;i++){
	if(imgs[i].id!=thisid){
		imgss+='{"id":"'+imgs[i].id+'","src":"'+imgs[i].src+'"},';
	}
}
localStorage.setItem('img',imgss);//更新本地数据库
result.removeChild(tid);//删除div
}
localStorage.setItem('img',"")//清空待上传数据库；

 function getImage() {//摄像头拍摄图片
 	var imgs=localStorage.getItem('img')||"";
    var cmr = plus.camera.getCamera(); 
    cmr.captureImage( function ( p ) {     
        plus.io.resolveLocalFileSystemURL( p, function ( entry ) {
                var localurl = entry.toLocalURL();//把拍照的目录路径，变成本地url路径，例如file:///........之类的。
                imgs+='{"id":"'+suijistr(4)+'","src":"'+localurl+'","img":"'+localurl.substr(localurl.lastIndexOf('/')+1)+'"},';
            	localStorage.setItem('img',imgs);
         		imgsplay(); //实时把图片显示到窗口
                });   
    },function(error) {
    	mui.toast('您未进行拍摄')
//          alert( "放弃本次拍摄"+error.message );
        }  
    );   
} 


function gallery(maxnum,lasnum){//从相册选择图片
	var imgs=localStorage.getItem('img')||"";
        plus.gallery.pick(
            function(paths){
            	if(paths.files.length>lasnum){
            		alert("对不起一次最多只允许上传"+lasnum+"个文件")
            		return false;
            	}
                var task = null;
                for(i in paths.files){
   					imgs+='{"id":"'+suijistr(4)+i+'","src":"'+paths.files[i]+'","img":"'+paths.files[i].substr(paths.files[i].lastIndexOf('/')+1)+'"},';
                }
                	localStorage.setItem('img',imgs);
             		imgsplay(); //实时把图片显示到窗口
            },
            function(e){mui.toast('取消了选择');},{multiple:true,maximum:lasnum,system:false,onmaxed:function(){ plus.nativeUI.alert('对不起本次最多只能选择'+lasnum+'张图片'); 
	}});// 
    }

function addup(maxnum,maxstrnum,minstrnum){//将本地数据库的图片组上传到服务器
	maxnum=maxnum || 9;//最多上传9张图
	maxstrnum=maxstrnum || 50;//文本框最多输入字数
	minstrnum=minstrnum || 10;//文本框最少输入字数
  var imgs=localStorage.getItem('img')||"";
//alert(imgs);
	var imgarr=[];
	if(imgs!=''){
	imgstr =imgs.substring(0, imgs.lastIndexOf(','));//去掉末尾逗号
	imgarr = eval('(['+imgs+'])');//字符串转成json对象
	num=imgarr.length||0;
	if(imgarr.length>maxnum){
		alert('对不起最多只能选择'+maxnum+'张图片');
		return false;
	};
	}
					var task = null;
                	task = plus.uploader.createUpload(
                    home.hos+'/microblog/publish',
                    { method:"POST",blocksize:204800,priority:100},
                    function (t,status){
                    	alert(JSON.stringify(t.responseText));//服务器返回数据
//                  	alert(status);//上传成功返回状态吗200
                        plus.nativeUI.closeWaiting();
                        console.log(t.responseText);//服务器返回数据返回信息
                        mui.toast('发布成功');
                    }
                );
                if(imgarr!==[]){
                for(i in imgarr){
						task.addFile(imgarr[i].src,{key:imgarr[i].id,'name':imgarr[i].src.substr(imgarr[i].src.lastIndexOf('/'))});
//						alert('添加图片'+imgarr[i].src);
                }
                }
                var	mess = document.getElementById('mess').value;
//              var opta = document.getElementById('opta');
//              var optb = document.getElementById('optb');
//              alert(opta.value+'关联298行测试完请删除'+optb.value); 
                if(mess.length<minstrnum){
                	 mui.alert('文本内容需要输入'+minstrnum+'字到'+maxstrnum+'字之间','您至少还需要输入'+(minstrnum-mess.length)+'个字');
                	return false;
                }
                if(mess.length>maxstrnum){
                	 mui.alert('文本内容需要输入'+minstrnum+'字到'+maxstrnum+'字之间','您需要删除'+(mess.length-maxstrnum)+'个字');
                	return false;
                }
//              alert(mess);
                task.addData("blog",mess); //key,string添加数据服务器post接收$_POST['biog'];
                task.addData("mtoken",home.mtoken); 
                task.addData("usertoken",my.token);
                task.addData("mid",my.mid);
                task.addData("authdate",my.authdate);
                task.addData("relation",opta.value);
                task.addData("relation_id",optb.value);
                localStorage.setItem('img',imgs);
//           alert(localStorage.getItem('img'));
                task.start();
                plus.nativeUI.showWaiting();
}
function imgsplay(){
	imgs= localStorage.getItem('img');
	imgs =imgs.substring(0, imgs.lastIndexOf(','));//去掉末尾逗号
	imgs = eval('(['+imgs+'])');//字符串转成json对象
	var imgss="";
	for (var i=0;i<imgs.length;i++) {
		imgss+='<div  id="'+imgs[i].id+'" onclick="deleteimg(this.id)" style="width:30%;float:left;height:100px;margin:1%;overflow:hidden;position:relative;font-size:10px;border-radius:5px;" ><span style="background:#FF6A6A;margin-top:0;border-radius:10px;width:18px;height:18px;position:absolute;text-align :center;color:#fff;line-height:18px; z-index:1;">X</span><img style=" position:relative; z-index:0;max-height: 200%;max-width: 200%;width: auto;height: auto;top: 50%;left: 50%;-webkit-transform: translateX(-50%) translateY(-50%);transform: translateX(-50%) translateY(-50%);" src="'+imgs[i].src+'" alt="" /></div>';
	}
	document.getElementById("result").innerHTML=imgss;
} 
</script>
</body>
</html>